<script lang="ts" setup>
import { ref, nextTick } from "vue";
import {
  startShareAnimation,
  endShareAnimation,
  reverseShareAnimation,
} from "@/utils/share";

const props = defineProps({
  auto: {
    type: Boolean,
    default: true,
  },
});

const isShowDetail = ref(false);
const defaultContainer = ref<HTMLElement | null>(null);
const showContainer = ref<HTMLElement | null>(null);

async function play() {
  if (!showContainer.value) return;
  let container = showContainer.value;
  if (container.children.length === 1) {
    container = showContainer.value.children[0] as HTMLElement;
  }
  endShareAnimation(container);
}

async function open() {
  if (!defaultContainer.value) return;
  let container = defaultContainer.value;
  if (container.children.length === 1) {
    container = container.children[0] as HTMLElement;
  }
  isShowDetail.value = true;
  startShareAnimation(container);
  await nextTick();
  props.auto && play();
  resetPosition();
}
/**
 * 用于解决absolute定位后container元素滚动导致显示位置不正确的问题
 */
function resetPosition() {
  const container = showContainer.value;
  if (!container || !container.offsetParent) return;
  const { left, top, width, height } =
    container.offsetParent.getBoundingClientRect();
  container.style.position = "fixed";
  container.style.width = width + "px";
  container.style.height = height + "px";
  container.style.transform = `translate(${left}px,${top}px)`;
}
async function close() {
  await reverseShareAnimation();
  isShowDetail.value = false;
}
</script>

<template>
  <section>
    <!-- 默认界面 -->
    <main
      ref="defaultContainer"
      @click="open()"
      class="container"
    >
      <slot :open="open"></slot>
    </main>
    <!-- 展示详情页面 -->
    <main
      v-if="isShowDetail"
      ref="showContainer"
      class="show-container"
    >
      <slot
        name="show"
        :close="close"
        :open="open"
        :play="play"
      ></slot>
    </main>
  </section>
</template>

<style lang="less" scoped>
section {
  .container {
    position: relative;
    width: 100%;
    height: 100%;
    z-index: 1;
  }
  .show-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow-y: auto;
    z-index: 2;
  }
}
</style>
